/*
 * @Author: yixin 
 * @Date: 2019-12-03 22:20:15 
 * @Last Modified by: yixin
 * @Last Modified time: 2019-12-11 22:40:30
 * 日期模态框
 */
import React, { PureComponent } from 'react'
import styles from './dateModal.less'
import dateUtil from '@/utils/date'
import PropTypes from 'prop-types'
import Toast from '@/utils/toast'

const months = [1,2,3,4,5,6,7,8,9,10,11,12]

export default class YearModal extends PureComponent {

  static propTypes = {
    submit: PropTypes.func.isRequired,
  }

  constructor(props){
    super(props);
    this.today = new Date();
    this.nowYear = this.today.getFullYear();
    this.nowMonth = this.today.getMonth() + 1;
    this.nowDay = this.today.getDate();
    this.state = {
      type: 2, // 0: 日 1: 月 2: 年
      days: [],
      visible: false,
      chooseDate: [this.nowDay,this.nowDay], //beginDate, endDate
      chooseMonth: this.nowMonth,
      chooseYear: (new Date()).getFullYear()
    }
  }

  componentDidMount() {
    this.getTime(this.nowYear, this.nowMonth)
  }

  show = () => {
    document.documentElement.style.position = 'fixed';
    document.documentElement.style.left = 0;
    document.documentElement.style.right = 0;
    document.body.style.overflow = 'hidden'; //隐藏滚动条
    this.setState({ visible: true });
  }
  
  dismiss = () => {
    document.documentElement.style.position = '';
    document.body.style.overflow = 'auto'; //隐藏滚动条
    this.setState({ visible: false });
  }

  /**
   * @param {String} y 年
   * @param {String} m 月
   * 获取前年月日表
   */
  getTime = (y, m) => {
    const { days, month, year } = dateUtil.getMonthDate(y, m);
    this.setState({
      days: this.formatDay(days),
      chooseMonth: month,
      chooseYear: year
    })
  }

  /**
   * @param {Array} days 当前月份日期数组
   * 将日期数组按每周分组
   */
  formatDay = (days) => {
    const tempTime = [];
    for (var i = 0, j = days.length; i < j; i += 7) {
      tempTime.push(days.slice(i, i + 7));
    }
    return tempTime
  }

  /**
   * @param {number} type 日历日月年切换
   */
  handleChangeType = (type) => {
    this.setState({ 
      type,
      chooseYear: this.nowYear,
      chooseMonth: this.nowMonth,
      chooseDate: [this.nowDay, this.nowDay]
    })
  }

  /**
   * @param {number} step 月数增减
   * 头部年/月按步数加减 type 0 按月减 1 按年减
   */
  handleChangeStep = (step) => {
    const { chooseMonth, chooseYear } = this.state;
    if(this.state.type==0){
      var newMonth = chooseMonth+step;
      var newYear = chooseYear
      if((newMonth)>12){
        newYear++;
        newMonth = 1;
      }else if(newMonth<1){
        newYear--;
        newMonth = 12;
      }
    }else{
      var newMonth = chooseMonth;
      var newYear = chooseYear+step;
    }
   
    this.getTime(newYear, newMonth);
  }

  /**
   * @param {number} 周index
   * @param {number} 天index
   * 日期选择-天
   */
  handleChooseDay = (weekindex, dayindex) => {
    const day = this.state.days[weekindex][dayindex].date;
    var tempDate = this.state.chooseDate.slice();
    if(this.state.chooseDate.length>1){ // beginTime和endTime都有，重置选中状态
      tempDate = [day]
    }else{
      tempDate.push(day)
    }
    this.setState({ chooseDate: tempDate.sort() })
  }

  /**
   * @param {number} 选择的月份
   * 日期选择-月
   */
  handleChooseMonth = (m) => {
    // 当月份大于当前月份则不操作
    if(m>this.nowMonth) return;
    this.setState({
      chooseMonth: m
    })
  }

    /**
   * @param {number} 选择的年
   * 日期选择-年
   */
  handleChooseYear = (y) => {
    // 当月份大于当前月份则不操作
    this.setState({
      chooseYear: y
    })
  }

  // 确认更新（返回年月日）
  submit = () => {
    switch (this.state.type) {
      // 按日选择
      case 0:
        if(this.state.chooseDate.length==0){ return Toast.error('请选择日期') }
        this.props.submit({
          beginDate: `${this.state.chooseYear}-${this.state.chooseMonth < 10 ? '0' + this.state.chooseMonth : this.state.chooseMonth}-${this.state.chooseDate[0] < 10 ? '0' + this.state.chooseDate[0] : this.state.chooseDate[0]}`,
          endDate: `${this.state.chooseYear}-${this.state.chooseMonth < 10 ? '0' + this.state.chooseMonth : this.state.chooseMonth}-${this.state.chooseDate[1] ? (this.state.chooseDate[1] < 10 ? '0' + this.state.chooseDate[1] : this.state.chooseDate[1]) : (this.state.chooseDate[0] < 10 ? '0' + this.state.chooseDate[0] : this.state.chooseDate[0])}`
        })
        break;
      // 按月选择
      case 1:
        this.props.submit({
          beginDate: `${this.state.chooseYear}-${this.state.chooseMonth < 10 ? '0'+this.state.chooseMonth : this.state.chooseMonth}-01`,
          endDate: `${this.state.chooseYear}-${this.state.chooseMonth < 10 ? '0'+this.state.chooseMonth : this.state.chooseMonth}-31`
        })
        break;
      case 2:
        this.props.submit({
          beginDate: `${this.state.chooseYear}-01-01`,
          endDate: `${this.state.chooseYear}-12-31`
        })
        break;
      default:
        break;
    }
  }

  render(){
    const { type, days, visible, chooseYear, chooseDate, chooseMonth } = this.state;
    if(!visible) return null;
    return (
      <div className={styles.dateModal} onClick={(e)=>{ this.setState({ visible: false })} }>
        <div className={styles.container} onClick={(e)=>{ e.stopPropagation(); }}>
          {/* <div className={styles.time}>
            <div onClick={()=>{ this.handleChangeType(0) }} className={styles.time_item} style={type==0 ? { backgroundColor: '#EA3A12', color: '#fff' } : {}}>日</div>
            <div onClick={()=>{ this.handleChangeType(1) }} className={styles.time_item} style={type==1 ? { backgroundColor: '#EA3A12', color: '#fff' } : {}}>月</div>
            <div onClick={()=>{ this.handleChangeType(2) }} className={styles.time_item} style={type==2 ? { backgroundColor: '#EA3A12', color: '#fff' } : {}}>年</div>
          </div> */}
          {type < 2 ? <div className={styles.header}>
            <img className={styles.header_icon} onClick={()=>{ this.handleChangeStep(-1) }} src={require('@/assets/img/date_left.png')} />
            {chooseYear}年{type==0 && `${chooseMonth}月`}
            {(chooseYear==this.nowYear && chooseMonth == this.nowMonth) ? <a></a> : <img className={styles.header_icon} src={require('@/assets/img/date_right.png')} onClick={()=>{ this.handleChangeStep(1) }} />}
          </div>: <div className={styles.header} />}
          {type==0 && <table className={styles.table}>
            <thead>
              <tr>
                <td>一</td>
                <td>二</td>
                <td>三</td>
                <td>四</td>
                <td>五</td>
                <td>六</td>
                <td>七</td>
              </tr>
            </thead>
            <tbody>
              {
                days && days.map((day, weekindex) => {
                  return (
                    <tr key={weekindex}>
                      {day.map((item, dayindex)=>(
                        <td key={dayindex} onClick={()=>{ !item.disabled && this.handleChooseDay(weekindex, dayindex) }}>
                          <div className={((item.date>=chooseDate[0]&&item.date<=(chooseDate[1]||chooseDate[0])) && styles.day_checked) + ' ' + (item.disabled && styles.day_disabled)}>{item.showDate}</div>
                        </td>
                      ))}
                    </tr>
                  )
                })
              }
            </tbody>
          </table>}
          {type == 1 && <div className={styles.month_box}>
            {
              months.map((m)=>( //大于当前月份的置灰
                <div onClick={()=>{ this.handleChooseMonth(m) }} key={m} className={styles.month_item + ' ' + (m>this.nowMonth&&chooseYear==this.nowYear && styles.month_disabled) + ' ' + (m==chooseMonth && styles.month_checked)}> 
                  {m}月
                </div>
              ))
            }
          </div>}
          {type == 2 &&
            <div>
              <div onClick={()=>{ this.handleChooseYear(this.nowYear-2) }} className={styles.year_item + ' ' + ((chooseYear == (this.nowYear-2)) && styles.year_checked)} style={{ marginBottom: 20 }}>{this.nowYear-2}</div>
              <div onClick={()=>{ this.handleChooseYear(this.nowYear-1) }} className={styles.year_item + ' ' + ((chooseYear == (this.nowYear-1)) && styles.year_checked)} style={{ marginBottom: 20 }}>{this.nowYear-1}</div>
              <div onClick={()=>{ this.handleChooseYear(this.nowYear) }} className={styles.year_item + ' ' + ((chooseYear == (this.nowYear)) && styles.year_checked)}>{this.nowYear}</div>
            </div>
          }
          <div className={styles.btn} onClick={this.submit}>
            确认更新
          </div>
        </div>
      </div>
    )
  }
}